package org.toycode.logindemo.application.tapestry.pages;

import java.net.ConnectException;
import javax.naming.NamingException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Errors;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.Label;
import org.apache.tapestry5.corelib.components.PasswordField;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.toycode.logindemo.application.util.EjbUtil;
import org.toycode.logindemo.entity.SystemUser;
import org.toycode.logindemo.service.SecurityServiceRemote;

/**
 * This class provides login for users.
 *
 * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
 * @version 1.0.0.1, Aug 19, 2009
 */
public class Login {

    /**
     * errors for form validation.
     */
    @Component
    private Errors errors;
    /**
     * message for name filed validation.
     */
    @Component(parameters = {"for=nameField"})
    private Label nameLabel;
    /**
     * user name field.
     */
    @Component(parameters = {"label=message:user-name", "value=name", "validate=required"})
    private TextField nameField;
    /**
     * message for password filed validation.
     */
    @Component(parameters = {"for=passwordField"})
    private Label passwordLabel;
    /**
     * user password field.
     */
    @Component(parameters = {"label=message:user-password", "value=password", "validate=required"})
    private PasswordField passwordField;
    /**
     * login form.
     */
    @Component
    private Form loginForm;
    /**
     * loggedin page.
     */
    @InjectPage
    private LoginSucceed loginSucceed;
    /**
     * name of the user to login.
     */
    @Property
    private String name;
    /**
     * password of the user to login.
     */
    @Property
    private String password;
    /**
     * logger.
     */
    private Logger logger = LoggerFactory.getLogger(Login.class);
    /**
     * security service.
     */
    private SecurityServiceRemote securityService;
    /**
     * messages.
     */
    @Inject
    private Messages messages;

    /**
     * Login form event handler method.
     *
     * @return if login succeed, return <code>loginSucceed</code>, otherwise,
     * returns <code>null</code>
     */
    public Object onSuccessFromLoginForm() {
        securityService = EjbUtil.getEjb(SecurityServiceRemote.class);
        if (securityService == null) {
            loginForm.recordError(messages.get("remote-connect-exception"));
            return null;
        }
        
        final SystemUser user = securityService.getUserByName(name);
        if (user != null) {
            final String passwordEncoded = DigestUtils.md5Hex(password);
            logger.debug("Logging user[name=" + name + ", password encoded=" + passwordEncoded + "]....");

            if (passwordEncoded.equals(user.getPassword())) {
                loginSucceed.setName(name);
                return loginSucceed;
            } else {
                loginForm.recordError(nameField, messages.get("password-error"));
                return null;
            }
        } else {
            loginForm.recordError(passwordField, messages.get("user-not-found"));
            return null;
        }
    }
}
